package model

import (
	"time"
	"github.com/astaxie/beego/orm"

)

type AllRead struct {
	Id int `orm:"column(id)" json:"id"`
	AccountId int `orm:"column(account_id)" json:"account_id"`
	ReadCount int64 `orm:"column(read_count)" json:"read_count"`
	FansCount int `orm:"column(fans_count)" json:"fans_count"`
	Time time.Time `orm:"column(time);index" json:"time"`
}

type TodayRead struct {
	AccountId int
	ReadCount int64
	FansCount int
	Time time.Time
	Nickname string
	Plat string
}

func AddAllRead(allRead *AllRead) error{
	orm := orm.NewOrm()
	allRead.Time = time.Now()
	_,err := orm.Insert(allRead)
	return err
}

func TodayReads()  ([]TodayRead,error){
	o := orm.NewOrm()
	sql := `select account_id,time,max(read_count) as read_count,max(fans_count) as fans_count,a.nick_name as nickname,a.plat from (select * from all_read where TO_DAYS(Now()) - TO_DAYS(time) < 2 and read_count > 0 order by time desc) b join account a where b.account_id = a.id  group by b.account_id,date_format(b.time,'%Y-%m.%d')`
	datas :=  []TodayRead{}
	_,err := o.Raw(sql).QueryRows(&datas)
	return datas,err
}


func UpdateAllRead(allRead *AllRead) error{
	orm := orm.NewOrm()
	_,err := orm.Update(allRead)
	return err
}

func ListAllRead()  ([]AllRead,error){
	o := orm.NewOrm()
	allReads :=  []AllRead{}
	s := "select * from all_read"
	_,err := o.Raw(s).QueryRows(&allReads)
	return allReads,err
}

func ListAllReadByPage(page int,size int)  (allReads []AllRead,count int,err error){
	o := orm.NewOrm()
	s := "select * from all_read order by id asc limit ?,?"
	_,err = o.Raw(s, (page-1)*size, size).QueryRows(&allReads)
	if err != nil{
		return nil,0,err
	}
	sql := `select count(*) from all_read`
	err = o.Raw(sql).QueryRow(&count)
	if err != nil{
		return nil,0,err
	}
	return allReads,count,err
}

func DeleteAllRead(id int) error{
	o := orm.NewOrm()
	if _,err := o.Delete(&AllRead{Id:id},"id");err != nil{
		return err
	}
	return nil
}

func GetAllReadById(id int) (*AllRead,error){
	o := orm.NewOrm()
	allRead := &AllRead{Id:id}
	if err := o.Read(allRead,"id");err != nil{
		return nil,err
	}
	return allRead,nil
}